<?php

/**
 * @name RewardController
 * @desc 控制器
 */
class RewardController extends AdminCommonController
{
    /**
     * 默认动作
     */
    public function indexAction(){
        $params = $this->jsonData();

        $row = $params['pageSize'] ?? 12;
        $page = $params['page'] ?? 1;

        $rewardLogModel = RewardLogModel::getSingleton();

        $cond = ['r.user_id'=> $this->admin_info['user_id'], 'r.status'=> 1];
        if(isset($params['type']) && $params['type'] != ''){
            $cond['r.type'] = trim($params['type']);
        }
        if(isset($params['month_date']) && $params['month_date']>0){
            $month_date = $params['month_date'];
            $dataArr = $rewardLogModel->getthemonth($params['month_date']);
        }else {
            $month_date = time();
            $dataArr = $rewardLogModel->getthemonth(time());
        }
        $cond['r.create_time#>='] = $dataArr['date_s'];
        $cond['r.create_time#<='] = $dataArr['date_e'];

        $list = $rewardLogModel->db
            ->field('r.*, u.moble, u.nick_name,o.order_no,uu.nick_name as o_user_nick_name')
            ->alias('r')
            ->join(['user', 'u'], ['r.from_user_id'=> 'u.user_id'], 'left join')
            ->join(['user', 'uu'], ['r.o_user_id'=> 'uu.user_id'], 'left join')
            ->join(['order', 'o'], ['r.order_id'=> 'o.order_id'], 'left join')
            ->where_c($cond)
            ->order('r.id desc')
            ->limit(($page - 1) * $row, $row)
            ->select();

        $total = $rewardLogModel->db
            ->alias('r')
            ->join(['user', 'u'], ['r.from_user_id'=> 'u.user_id'], 'left join')
            ->join(['user', 'uu'], ['r.o_user_id'=> 'uu.user_id'], 'left join')
            ->join(['order', 'o'], ['r.order_id'=> 'o.order_no'], 'left join')
            ->where_c($cond)
            ->count();

        foreach($list as &$val){
            if($val['from_user_type'] == 0){
                $val['user_type_text'] = '普通会员';
            }
            if($val['from_user_type'] == 1){
                $val['user_type_text'] = '网店';
            }
            if($val['from_user_type'] == 2){
                $val['user_type_text'] = '实体店';
            }
            $val['type_show'] = RewardLogModel::$typeText[$val['type']];

            $val['ratio_show'] = $val['ratio']*100 . '%';
            $val['self_ratio_show'] = $val['self_ratio']*100 . '%';
            if($val['o_user_nick_name']){
                $val['o_ratio_show'] = $val['o_ratio']*100 . '%';
            }else {
                $val['o_ratio_show'] = '--';
                $val['o_user_nick_name'] = '--';
            }
        }

        //所有提成积分
        $pointTotal = $rewardLogModel->db
            ->field('sum(r.point) as point_total')
            ->alias('r')
            ->join(['user', 'u'], ['r.from_user_id'=> 'u.user_id'], 'left join')
            ->join(['order', 'o'], ['r.order_id'=> 'o.order_no'], 'left join')
            ->where_c($cond)
            ->find();

        $data = [
            'list' => $list,
            'total' => intval($total),
            'current'   => intval($page),
            'pageSize'  => intval($row),
            'page'  => intval($page),
            'pageNum'   => ceil($total/$row),
            'month_date'    => date('Y-m', $month_date),
            'point_total'   => $pointTotal['point_total']
        ];

        $this->ajaxReturn(0, '', $data);
    }

    //业绩查询（只计算直营业绩）
    public function kpiAction(){
        $params = $this->jsonData();

        $row = $params['pageSize'] ?? 12;
        $page = $params['page'] ?? 1;

        $rewardLogModel = RewardLogModel::getSingleton();

        $cond = ['r.user_id'=> $this->admin_info['user_id'], 'r.status'=> 1, 'type'=> 1];
        if(isset($params['month_date']) && $params['month_date']>0){
            $month_date = $params['month_date'];
            $dataArr = $rewardLogModel->getthemonth($params['month_date']);
        }else {
            $month_date = time();
            $dataArr = $rewardLogModel->getthemonth(time());
        }
        $cond['r.create_time#>='] = $dataArr['date_s'];
        $cond['r.create_time#<='] = $dataArr['date_e'];

        $list = $rewardLogModel->db
            ->field('r.*, u.moble, u.nick_name,o.order_no')
            ->alias('r')
            ->join(['user', 'u'], ['r.from_user_id'=> 'u.user_id'], 'left join')
            ->join(['order', 'o'], ['r.order_id'=> 'o.order_id'], 'left join')
            ->where_c($cond)
            ->order('r.id desc')
            ->limit(($page - 1) * $row, $row)
            ->select();

        $total = $rewardLogModel->db
            ->alias('r')
            ->join(['user', 'u'], ['r.from_user_id'=> 'u.user_id'], 'left join')
            ->join(['order', 'o'], ['r.order_id'=> 'o.order_no'], 'left join')
            ->where_c($cond)
            ->count();

        foreach($list as &$val){

        }

        //所有提成积分
        $moneyTotal = $rewardLogModel->db
            ->field('sum(r.money) as money_total')
            ->alias('r')
            ->join(['user', 'u'], ['r.from_user_id'=> 'u.user_id'], 'left join')
            ->join(['order', 'o'], ['r.order_id'=> 'o.order_no'], 'left join')
            ->where_c($cond)
            ->find();
        //提成比例
        $ratio = $rewardLogModel->monthRatio($moneyTotal['money_total']);

        $data = [
            'list' => $list,
            'total' => intval($total),
            'current'   => intval($page),
            'pageSize'  => intval($row),
            'page'  => intval($page),
            'pageNum'   => ceil($total/$row),
            'month_date'    => date('Y-m', $month_date),
            'money_total'   => $moneyTotal['money_total'],
            'ratio'     => $ratio*100 . '%'
        ];

        $this->ajaxReturn(0, '', $data);
    }

    //出入账记录
    public function kpilogAction(){
        $params = $this->jsonData();

        $row = $params['pageSize'] ?? 12;
        $page = $params['page'] ?? 1;

        $kpiLogModel = KpiLogModel::getSingleton();

        $cond = ['user_id'=> $this->admin_info['user_id']];
        if(isset($params['cate']) && $params['cate'] != ''){
            $cond['cate'] = $params['cate'];
        }
        if(isset($params['date_s']) && $params['date_s'] != ''){
            $cond['create_time#>='] = $params['date_s'];
        }
        if(isset($params['date_e']) && $params['date_e'] != ''){
            $cond['create_time#<='] = $params['date_e'];
        }

        $list = $kpiLogModel->db
            ->where($cond)
            ->order('create_time desc')
            ->limit(($page - 1) * $row, $row)
            ->select();

        $total = $kpiLogModel->db
            ->where($cond)
            ->count();

        foreach($list as &$val){
            $val['type_text'] = KpiLogModel::$typeText[$val['type']];
            $val['cate_text'] = KpiLogModel::$cateText[$val['cate']];
            if($val['cate'] == 1){
                $month = date('m', $val['month_date']);
                $val['description'] = intval($month).'月份积分奖励入账';
            }
            if($val['cate'] == 2){
                $val['description'] = '提现申请打款,提现工单号：' . $val['withdraw_no'];
            }
        }

        $data = [
            'list' => $list,
            'total' => intval($total),
            'current'   => intval($page),
            'pageSize'  => intval($row),
            'page'  => intval($page),
            'pageNum'   => ceil($total/$row),
        ];

        $this->ajaxReturn(0, '', $data);
    }

    //提现申请
    public function withdrawaddAction(){
        $params = $this->jsonData();
        if(!isset($params['point']) || !floatval($params['point'])){
            $this->ajaxReturn(400,'必须输入提现金额');
        }
        if(!isset($params['user_bank_id']) || !floatval($params['user_bank_id'])){
            $this->ajaxReturn(400,'必须选择银卡卡');
        }

        $point = floatval($params['point']);

        $withdrawModel = WithdrawModel::getSingleton();
        //判断是否有未处理的工单
        $exsit = $withdrawModel->find(['user_id'=> $this->admin_info['user_id'], 'status'=> 0]);
        if($exsit){
            $this->ajaxReturn(400, '您有未处理的提现工单，请等待系统处理完');
        }

        //最后一笔交易额
        $lastKpilog = KpiLogModel::getSingleton()->db
            ->where(['user_id'=> $this->admin_info['user_id']])
            ->order('create_time desc')
            ->find();
        if(!$lastKpilog || $lastKpilog['point_after'] < $point){
            $this->ajaxReturn(400, '积分不足');
        }

        $withdraw_no = date('Hms').rand(111111, 999999);
        $addData = [
            'withdraw_no'       => $withdraw_no,
            'user_id'          => $this->admin_info['user_id'],
            'status'          => 0,
            'point'         => $point,
            'user_bank_id'  => $params['user_bank_id']
        ];

        if(!$withdrawModel->add($addData)){
            $this->ajaxReturn(400, '申请失败');
        }
        $this->ajaxReturn(0, '申请成功');
    }

    //提现记录
    public function withdrawlogAction(){
        $params = $this->jsonData();

        $row = $params['pageSize'] ?? 12;
        $page = $params['page'] ?? 1;

        $withdrawModel = WithdrawModel::getSingleton();

        if($this->admin_info['admin_type'] == 3){
            $cond = [];
        }else {
            $cond = ['user_id'=> $this->admin_info['user_id']];
        }
        if(isset($params['status']) && $params['status'] != ''){
            $cond['status'] = $params['status'];
        }
        if(isset($params['date_s']) && $params['date_s'] != ''){
            $cond['create_time#>='] = $params['date_s'];
        }
        if(isset($params['date_e']) && $params['date_e'] != ''){
            $cond['create_time#<='] = $params['date_e'];
        }

        $list = $withdrawModel->db
            ->where($cond)
            ->order('create_time desc')
            ->limit(($page - 1) * $row, $row)
            ->select();

        $total = $withdrawModel->db
            ->where($cond)
            ->count();

        foreach($list as &$val){
            $val['status_text'] = WithdrawModel::$statusText[$val['status']];
            $bank = UserbankModel::getSingleton()->find(['id'=> $val['user_bank_id']]);
            $val['bank_info'] = $bank['bank_no'] . '('. $bank['bank_name'] .')';
        }

        $data = [
            'list' => $list,
            'total' => intval($total),
            'current'   => intval($page),
            'pageSize'  => intval($row),
            'page'  => intval($page),
            'pageNum'   => ceil($total/$row),
        ];

        $this->ajaxReturn(0, '', $data);
    }

    //用户可用积分
    public function canpointAction(){
        $lastKpilog = KpiLogModel::getSingleton()->db
            ->where(['user_id'=> $this->admin_info['user_id']])
            ->order('create_time desc')
            ->find();
        if(!$lastKpilog){
            $point = 0;
        }else {
            $point = $lastKpilog['point_after'];
        }

        $this->ajaxReturn(0, 'success', $point);
    }

    //处理提现记录
    public function checkwithdrawAction(){
        $params = $this->jsonData();
        if(!isset($params['withdraw_id']) || !$params['withdraw_id']){
            $this->ajaxReturn(400,'必须选择一个记录');
        }
        if(!isset($params['status']) || $params['status'] == ''){
            $this->ajaxReturn(400,'必须指明处理结果');
        }

        $withdrawModel = WithdrawModel::getSingleton();
        $kpiLogModel = KpiLogModel::getSingleton();

        $withdrawInfo = $withdrawModel->find(['withdraw_id'=> $params['withdraw_id']]);
        if($withdrawInfo['status'] == $params['status']){
            $this->ajaxReturn(400, '请勿重复操作');
        }

        //如果拒绝
        if($params['status'] == 2){
            $updateData = [
                'status'    => 2,
                'check_text'    => $params['check_text'],
                'check_time'    => time(),
                'admin_id'      => $this->admin_info['admin_id']
            ];
            if(!$withdrawModel->update(['withdraw_id'=> $params['withdraw_id']], $updateData)){
                $this->ajaxReturn(400, '操作失败');
            }
        }else if($params['status'] == 1){
            //防止重复点击
            try{
                \Vendor\DB::startTrans();

                //修改状态
                $updateData = [
                    'status'    => 1,
                    'check_time'    => time(),
                    'admin_id'      => $this->admin_info['admin_id']
                ];
                if(!$withdrawModel->update(['withdraw_id'=> $params['withdraw_id']], $updateData)){
                    \Vendor\DB::rollback();
                    $this->ajaxReturn(400, '操作失败');
                }
                //记录kpi_log记录
                $lastKpilog = KpiLogModel::getSingleton()->db
                    ->where(['user_id'=> $withdrawInfo['user_id']])
                    ->order('create_time desc')
                    ->find();
                if(!$lastKpilog){
                    $point_before = 0;
                }else {
                    $point_before = $lastKpilog['point_after'];
                }
                if($point_before < $withdrawInfo['point']){
                    $this->ajaxReturn(400, '积分不足');
                }
                $addData = [
                    'user_id'       => $withdrawInfo['user_id'],
                    'type'          => 2,
                    'cate'          => 2,
                    'point_before'  => $point_before,
                    'point'         => $withdrawInfo['point'],
                    'point_after'   => $point_before - $withdrawInfo['point'],
                    'ratio'         => 0,
                    'month_kpi'     => 0,
                    'ratio_month'   => 0,
                    'year_kpi'      => 0,
                    'ratio_year'    => 0,
                    'month_date'    => 0,
                    'withdraw_no'   => $withdrawInfo['withdraw_no']
                ];
                if(!$kpiLogModel->add($addData)){
                    \Vendor\DB::rollback();
                    $this->ajaxReturn(400, '操作失败');
                }

                \Vendor\DB::commit();
            }catch(Exception $e){
                \Vendor\DB::rollback();
                $this->ajaxReturn(400, '下单失败，请返回重试', $e->getMessage());
            }

        }else {
            $this->ajaxReturn(400, '操作失败');
        }

        $this->ajaxReturn(0, '操作成功');
    }





    //当前奖励详情
    public function reportAction(){

        $params = $this->jsonData();
        if(!isset($params['date_time']) || !$params['date_time']){
           $params['date_time'] = time();
        }

        //直营数据
        $oneData = $this->getUserKpi($this->admin_info['user_id'], $params['date_time']);
        //团队奖励
//        $twoData = $this->getShopKpi($this->admin_info['user_id'], $this->admin_info['user_type'], $params['date_time'], $oneData['ratioTotalNum']);
        $twoData = [];
        $returnData = [
            'one'   => $oneData,
            'two'   => $twoData,
        ];

        $this->ajaxReturn(0, 'success', $returnData);
    }

    //计算指定会员的直营业绩
    private function getUserKpi($user_id, $date_time){

        //会员当月直营积分数据
        $kpiData = $this->getReferUserOrderPoint($user_id, $date_time);
        //会员提成比例
        $ratioData = $this->getUserRatio($user_id, $date_time);
        //自己的直营提成
        $pointOne = $kpiData['kpiPointBase'] * ($ratioData['monthRatio'] + $ratioData['yearRatio']);

        return [
            'kpiPointBase'      => $kpiData['kpiPointBase'] ?? 0,      //本月总积分
            'prevMonthMoney'    => $ratioData['prevMonthMoney'] ?? 0,      //上月业绩
            'yearMonthMoney'    => $ratioData['yearMonthMoney'] ?? 0,
            'monthRatio'        => ($ratioData['monthRatio']*100) . '%',
            'yearRatio'         => ($ratioData['yearRatio']*100) . '%',
            'ratioTotal'        => ($ratioData['ratioTotal'])*100 . '%',
            'ratioTotalNum'     => $ratioData['ratioTotal'],
            'pointOne'          => $pointOne ?? 0,
            'list'              => $kpiData['list']
        ];
    }

    //计算会员网店身份的5% 积分奖励
    private function getShopKpi($user_id, $user_type, $date_time, $user_ratio){
        $userModel = UserModel::getSingleton();

        $point = 0;

        if($user_type == 1){
            //旗下所有网店
            $shopUser = $userModel->findAll(['refer_user_id'=> $user_id, 'user_type#>'=> 0], 'user_type,user_id,nick_name');
            foreach ($shopUser as $key=>&$val){
                //所属身份
                $val['user_type_text'] = $val['user_type']==1? '网店': '实体店';
                //积分基数
                $thisKpiData = $this->getReferUserOrderPoint($val['user_id'], $date_time);
                //无业绩则跳出
                if(!$thisKpiData['kpiPointBase']){
                    unset($shopUser[$key]);
                    continue;
                }
                $val['kpiPointBase'] = $thisKpiData['kpiPointBase'];
                //积分比例
                $ratioData = $this->getUserRatio($val['user_id'], $date_time);
                $val['ratioTotal'] = $ratioData['ratioTotal'];
                $val['upPoint'] = 0;
                if($user_ratio >= $ratioData['ratioTotal']){
                    $ratio = 0.05;
                    $val['upPoint'] = $thisKpiData['kpiPointBase'] * $ratio;
                    $val['ratio'] = $ratio;
                    $point += $val['upPoint'];
                }else {
                    $val['upPoint'] = '无法获得提成';
                    $val['ratio'] = '--';
                }
            }
        }
        if($user_type == 2){
            //旗下所有网店（包括网店的网店）
            $shopUser = $userModel->findAll(['refer_user_id|shop_user_id'=> $user_id], 'shop_user_id,refer_user_id,user_type,user_id,nick_name');
//          print_r($shopUser);exit;
            foreach ($shopUser as $key=>&$val){
                //所属身份
                $val['user_type_text'] = $val['user_type']==1? '网店': '实体店';
                //积分基数
                $thisKpiData = $this->getReferUserOrderPoint($val['user_id'], $date_time);
                //无业绩则跳出
                if(!$thisKpiData['kpiPointBase']){
                    unset($shopUser[$key]);
                    continue;
                }
                $val['kpiPointBase'] = $thisKpiData['kpiPointBase'];
                //积分比例
                $ratioData = $this->getUserRatio($val['user_id'], $date_time);
                $val['ratioTotal'] = $ratioData['ratioTotal'];
                $val['upPoint'] = 0;
                if($user_ratio >= $ratioData['ratioTotal']){
                    $ratio = 0.05;
                    if($val['shop_user_id'] == $val['refer_user_id']){
                        $ratio = 0.2;
                    }
                    $val['upPoint'] = $thisKpiData['kpiPointBase'] * $ratio;
                    $val['ratio'] = $ratio;
                    $point += $val['upPoint'];

                }else {
                    $val['upPoint'] = '无法获得提成';
                    $val['ratio'] = '--';
                }

            }
        }

        return ['point'=> $point, 'list'=> $shopUser];
    }

    //获取会员的积分基数（推荐的所有会员订单积分总额）
    private function getReferUserOrderPoint($user_id, $date_time){
        //本月时间范围
        $dayArr = $this->getthemonth($date_time);
        $userModel = UserModel::getSingleton();
        $orderModel = OrderModel::getSingleton();
        //旗下的普通购物客户
        $childUser = $userModel->findAll(['refer_user_id'=> $user_id, 'user_type'=> 0], 'user_id');
        $userIdArr = [];
        foreach ($childUser as $val){
            $userIdArr[] = $val['user_id'];
        }
        $kpiPointBase = 0;
        //本月积分
        $cond = [
            'status_three_time#>='  => $dayArr['date_s'],
            'status_three_time#<='  => $dayArr['date_e'],
            'o.user_id#in'=> $userIdArr,
            'o.status#in'=> [3,8]
        ];
        $orderList = $orderModel->db
            ->field('o.user_id,sum(o.kpi_point) as kpi_point_total,u.nick_name,u.user_type,count(*) as order_count')
            ->alias('o')
            ->join(['user', 'u'], ['o.user_id'=> 'u.user_id'], 'left join')
            ->groupby('o.user_id')
            ->order('kpi_point_total desc')
            ->where_c($cond) //计算已完成和不退款的订单
            ->select();
        foreach ($orderList as &$val){
            $val['user_type_text'] = $val['user_type'] ==0? '普通会员': '其他';
            $kpiPointBase += $val['kpi_point_total'];
        }
        return ['kpiPointBase'=> $kpiPointBase, 'list'=> $orderList];
    }

    //获取会员的提成级别
    private function getUserRatio($user_id, $date_time){
        //上月时间
        $prevMonth = $this->getprevmonth($date_time);
        //上月时间范围
        $prevDayArr = $this->getthemonth($prevMonth);
        //本年度开始时间
        $yearStartTime = $this->yearStartTime();

        $userModel = UserModel::getSingleton();
        $orderModel = OrderModel::getSingleton();

        $childUser = $userModel->findAll(['refer_user_id'=> $user_id], 'user_id');
        $userIdArr = [];
        foreach ($childUser as $val){
            $userIdArr[] = $val['user_id'];
        }
        //上月总业绩
        $cond = [
            'status_three_time#>='  => $prevDayArr['date_s'],
            'status_three_time#<='  => $prevDayArr['date_e'],
            'o.user_id#in'=> $userIdArr,
            'o.status#in'=> [3,8]
        ];
        $prevOrderData = $orderModel->db
            ->field('sum(o.total_money) as total_money_total')
            ->alias('o')
            ->join(['user', 'u'], ['o.user_id'=> 'u.user_id'], 'left join')
            ->where_c($cond) //计算已完成和不退款的订单
            ->find();
        $prevMonthMoney = $prevOrderData['total_money_total'];
        $monthRatio = $this->monthRatio($prevMonthMoney);

        //本年度总业绩
        $cond = [
            'status_three_time#>='  => $yearStartTime,
            'o.user_id#in'=> $userIdArr,
            'o.status#in'=> [3,8]
        ];
        $yearOrderData = $orderModel->db
            ->field('sum(o.total_money) as total_money_total')
            ->alias('o')
            ->join(['user', 'u'], ['o.user_id'=> 'u.user_id'], 'left join')
            ->where_c($cond) //计算已完成和不退款的订单
            ->find();
        $yearMonthMoney = $yearOrderData['total_money_total'];
        $yearRatio = $this->yearRatio($yearMonthMoney);

        return [
            'prevMonthMoney'    => $prevMonthMoney,
            'monthRatio'        => $monthRatio,
            'yearMonthMoney'    => $yearMonthMoney,
            'yearRatio'         => $yearRatio,
            'ratioTotal'        => $monthRatio + $yearRatio
        ];
    }

    //指定月份开始结束时间
    private function getthemonth($date)
    {
        $firstday = date('Y-m-01', $date).' 00:00:00';
        $lastday = date('Y-m-d', strtotime("$firstday +1 month -1 day")).' 00:00:00';
        return array('date_s'=> strtotime($firstday),'date_e'=> strtotime($lastday));
    }

    //指定月份上月时间
    public function getprevmonth($date){
        $firstday = date('Y-m-d', $date);
        $prevMonth = date('Y-m-d', strtotime("$firstday -1 month"));
        return strtotime($prevMonth);
    }

    //本年度开始时间
    public function yearStartTime(){
        return strtotime(date('Y-01-01 00:00:00', time()));
    }

    //月份业绩提成配置
    public function monthRatio($kpi){
        $ratio = 0.1;
        if($kpi>=10000 && $kpi<20000){
            $ratio = 0.2;
        }
        if($kpi>=20000 && $kpi<30000){
            $ratio = 0.3;
        }
        if($kpi>=30000){
            $ratio = 0.4;
        }
        return $ratio;
    }

    //年度业绩提成配置
    public function yearRatio($kpi){
        $ratio = 0.1;
        if($kpi>=20000 && $kpi<30000){
            $ratio = 0.2;
        }
        if($kpi>=30000 && $kpi<50000){
            $ratio = 0.3;
        }
        if($kpi>=50000){
            $ratio = 0.4;
        }
        return $ratio;
    }
}

